package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"vueBasic/app"
	"vueBasic/app/admin/filter"
	"vueBasic/app/common/business"
	"vueBasic/app/common/response"
	"vueBasic/extend/captcha"
	"vueBasic/extend/utils"
)

var LoginC = new(loginController)

type loginController struct {
	app.BaseController
}

func (con *loginController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/login/index.html", gin.H{})
}

// 登录操作
func (con *loginController) DoLogin(c *gin.Context) {
	if c.Request.Method != "POST" {
		response.Fail(c, "请求方式有误")
		return
	}
	req := filter.AdminLoginReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	nickname, err := business.LoginB.DoLogin(&req, c)
	if err != nil {
		response.Fail(c, err.Error())
		return
	} else {
		response.Success(c, "登录成功", gin.H{
			"nickname": nickname,
		})
	}
}

// 获取验证码
func (con *loginController) Verify(c *gin.Context) {
	site_title := c.MustGet("site_title")
	response.Success(c, "返回成功", map[string]any{
		"captcha":     captcha.MakeCaptcha(),
		"site_title":  site_title,
		"success_url": "/admin/index/index",
	})
}

// 退出
func (con *loginController) Logout(c *gin.Context) {
	utils.DelSession("userToken", c)
	response.Success(c, "退出登录成功", nil)
}
